package com.ipan.weixin.util;

import java.util.Arrays;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.util.Args;

/**
 * 通信接口安全验证
 * 
 * @author iPan
 * @version 2013-12-25
 */
public class WxMessageVerifyUtils {

	public static String encode(String timestamp, String nonce, String token) {
		String[] params = new String[]{timestamp, nonce, token};
		Arrays.sort(params);
		String preText = params[0] + params[1] + params[2];
		return DigestUtils.shaHex(preText);
	}
	
	public static boolean verify(String signature, String timestamp, String nonce, String token) {
		Args.notNull(signature, "signature");
		Args.notNull(timestamp, "timestamp");
		Args.notNull(nonce, "nonce");
		Args.notNull(token, "token");
		String encodeStr = encode(timestamp, nonce, token);
		return signature.equals(encodeStr);
	}
	
//	public static void main(String[] args) {
//		String signature = "4c120e307884003bf0ea7867ac1ea663ea450b8b";
//		String nonce = "1387975544";
//		String timestamp = "1388071282";
//		String token = "ipan_weixin_web";
//		System.out.println(verify(signature, timestamp, nonce, token));
//	}
}
